package com.market.domain.activity.service.quota;


import com.alibaba.fastjson.JSON;
import com.market.domain.activity.model.aggregate.CreateQuotaOrderAggregate;
import com.market.domain.activity.model.entity.*;
import com.market.domain.activity.repository.IActivityRepository;
import com.market.domain.activity.service.IRaffleActivityAccountQuotaService;
import com.market.domain.activity.service.quota.policy.ITradePolicy;
import com.market.domain.activity.service.quota.rule.IActionChain;
import com.market.domain.activity.service.quota.rule.factory.DefaultActivityChainFactory;
import com.market.types.enums.ResponseCode;
import com.market.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

//抽奖活动抽象类，定义标准的流程
@Slf4j
public abstract class AbstractRaffleActivityAccountQuota extends RaffleActivityAccountQuotaSupport implements IRaffleActivityAccountQuotaService {

    private final Map<String, ITradePolicy> tradePolicyGroup;

    public AbstractRaffleActivityAccountQuota(DefaultActivityChainFactory activityChainFactory, IActivityRepository activityRepository, Map<String, ITradePolicy> tradePolicyGroup) {
        super(activityChainFactory, activityRepository);
        this.tradePolicyGroup = tradePolicyGroup;
    }


    @Override
    public UnpaidActivityOrderEntity createSkuRechargeOrder(SkuRechargeEntity skuRechargeEntity) {

        //1. 参数校验
        String userId = skuRechargeEntity.getUserId();
        Long sku = skuRechargeEntity.getSku();
        String outBusinessNo = skuRechargeEntity.getOutBusinessNo();
        if (null == sku || StringUtils.isBlank(userId) || StringUtils.isBlank(outBusinessNo)) {
            throw new AppException(ResponseCode.ILLEGAL_PARAMETER.getCode(), ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }
        //2.查询是否存在未支付成功订单
        UnpaidActivityOrderEntity unpaidActivityOrderEntity = activityRepository.queryUnpaidActivityOrder(skuRechargeEntity);
        if(null != unpaidActivityOrderEntity)
            return unpaidActivityOrderEntity;
        //3. 不存在未支付订单：查询基础信息
        // 3.1 通过sku查询活动信息
        ActivitySkuEntity activitySkuEntity = queryActivitySku(sku);
        // 3.2 查询活动信息
        ActivityEntity activityEntity = queryRaffleActivityByActivityId(activitySkuEntity.getActivityId());
        // 3.3 查询次数信息（用户在活动上可参与的次数）
        ActivityCountEntity activityCountEntity = queryRaffleActivityCountByActivityCountId(activitySkuEntity.getActivityCountId());

        //3.活动动作规则校验
        IActionChain actionChain = activityChainFactory.openActionChain();
            //不需要返回值，校验不通过会抛出异常
        actionChain.action(activitySkuEntity, activityEntity, activityCountEntity);

        //4.构建订单聚合对象
        CreateQuotaOrderAggregate createOrderAggregate = buildOrderAggregate(skuRechargeEntity, activitySkuEntity, activityEntity, activityCountEntity);

        //5.保存订单,根据交易类型的策略
        ITradePolicy tradePolicy = tradePolicyGroup.get(skuRechargeEntity.getOrderTradeTypeVO().getCode());
        tradePolicy.trade(createOrderAggregate);

        //6.返回单号
        ActivityOrderEntity activityOrderEntity = createOrderAggregate.getActivityOrderEntity();
               return UnpaidActivityOrderEntity.builder()
                              .userId(userId)
                              .orderId(activityOrderEntity.getOrderId())
                              .outBusinessNo(activityOrderEntity.getOutBusinessNo())
                              .payAmount(activityOrderEntity.getPayAmount())
                              .build();
    }


    protected abstract CreateQuotaOrderAggregate buildOrderAggregate(SkuRechargeEntity skuRechargeEntity, ActivitySkuEntity activitySkuEntity, ActivityEntity activityEntity, ActivityCountEntity activityCountEntity);


}
